package com.ruoyi.order.service.impl;

import java.io.*;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OConvertUtils;
import com.ruoyi.order.domain.*;
import com.ruoyi.order.mapper.*;
import com.ruoyi.order.service.ITbProductSpecificationService;
import com.ruoyi.order.vo.ProductPlusVo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.order.service.ITbProductService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import static com.ruoyi.common.utils.SecurityUtils.getUsername;

/**
 * 商品Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-19
 */
@Service
public class TbProductServiceImpl implements ITbProductService
{
    @Autowired
    private TbProductMapper tbProductMapper;
    @Autowired
    private TbProductWholesaleMapper tbProductWholesaleMapper;
    @Autowired
    private TbProductWholeasalePriceMapper tbProductWholeasalePriceMapper;
    @Autowired
    private TbProductSpecificationMapper tbProductSpecificationMapper;

    /**
     * 查询商品
     * 
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public TbProduct selectTbProductById(Long id)
    {
        return tbProductMapper.selectTbProductById(id);
    }

    /**
     * 查询商品列表
     * 
     * @param tbProduct 商品
     * @return 商品
     */
    @Override
    public List<TbProduct> selectTbProductList(TbProduct tbProduct)
    {
        return tbProductMapper.selectTbProductList(tbProduct);
    }

    @Override
    public List<JSONObject> selectProductVoList(ProductPlusVo productPlusVo) {
        List<ProductPlusVo> productPlusVos = tbProductMapper.selectProductVoList(productPlusVo);
        Long productTypeId = productPlusVo.getProductTypeId();
        List<Long> typeIds = new ArrayList<>();
        typeIds.add(productTypeId);

        List<JSONObject> returnJson = new ArrayList<>();
        for (ProductPlusVo productPlusVo1 : productPlusVos) {
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(productPlusVo1));
            List<TbProductWholesale> tbProductWholesales = tbProductWholesaleMapper.selectTbproductWholesaleListByTypeIds(typeIds);
            if (OConvertUtils.isNotEmpty(tbProductWholesales)){
                // 批量查询 规格
                List<Long> specIds = productPlusVos.stream().map(ProductPlusVo::getSpecificationId).collect(Collectors.toList());
                // 批发规格
                List<Long> wholeIds = tbProductWholesales.stream().map(TbProductWholesale::getId).collect(Collectors.toList());
                if (OConvertUtils.listIsNotEmpty(wholeIds) &&OConvertUtils.listIsNotEmpty(specIds)){
                    List<TbProductWholeasalePrice> tbProductWholeasalePrices = tbProductWholeasalePriceMapper.ListBySpecificationIdsAndWholeasaleId(specIds, wholeIds);
                    for (TbProductWholesale wholesale : tbProductWholesales){
                        List<TbProductWholeasalePrice> collect = tbProductWholeasalePrices.stream().filter(tbProductWholeasalePrice -> tbProductWholeasalePrice.getProductWholeasaleId().equals(wholesale.getId())&& tbProductWholeasalePrice.getProductSpecification().equals(productPlusVo1.getSpecificationId()) ).collect(Collectors.toList());
                        if (OConvertUtils.listIsNotEmpty(collect)){
                            jsonObject.put(wholesale.getNum()+"+",collect.get(0).getPrice());
                        }else{
                            jsonObject.put(wholesale.getNum()+"+",null);
                        }
                    }
                }
            }
            returnJson.add(jsonObject);
        }
        // 获取所有单价
        return returnJson;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addProductVo(JSONObject jsonObject) {
        ProductPlusVo productPlusVo=jsonObject.toJavaObject(ProductPlusVo.class);
        Long productTypeId = productPlusVo.getProductTypeId();

        TbProduct param =new TbProduct();
        param.setProductName(productPlusVo.getProductName());
        List<TbProduct> tbProducts = tbProductMapper.selectTbProductList(param);
        if (OConvertUtils.listIsEmpty(tbProducts)){
            // 如果没有商品则进行添加商品
            param.setProductName(productPlusVo.getProductName());
            param.setProductOtherName(productPlusVo.getProductOtherName());
            param.setProductTypeId(productTypeId);
            this.insertTbProduct(param);
        }else{
            param.setId(tbProducts.get(0).getId());
            param.setProductTypeId(productTypeId);
        }
        // 添加商品规格
        TbProductSpecification tbProductSpecification =new TbProductSpecification();
        tbProductSpecification.setProductPrice(productPlusVo.getProductPrice());
        tbProductSpecification.setProductId(param.getId());
        tbProductSpecification.setProductSpecification(productPlusVo.getProductSpecification());
        tbProductSpecification.setProductUrl(productPlusVo.getProductUrl());
        tbProductSpecification.setProductNo(productPlusVo.getProductNo());
        tbProductSpecificationMapper.insertTbProductSpecification(tbProductSpecification);

        //查询商品批发规格
        TbProductWholesale tbProductWholesale = new TbProductWholesale();
        tbProductWholesale.setProductTypeId(productTypeId);
        List<TbProductWholesale> tbProductWholesales = tbProductWholesaleMapper.selectTbProductWholesaleList(tbProductWholesale);
        if (OConvertUtils.listIsNotEmpty(tbProductWholesales)){
            for (TbProductWholesale tbProductWholesale1:tbProductWholesales){
                String string = jsonObject.getString(tbProductWholesale1.getNum() + "+");
                if (OConvertUtils.isNotEmpty(string)){
                    // 添加商品批发价格
                    TbProductWholeasalePrice tbProductWholeasalePrice =new TbProductWholeasalePrice();
                    tbProductWholeasalePrice.setProductSpecification(tbProductSpecification.getId());
                    tbProductWholeasalePrice.setProductWholeasaleId(tbProductWholesale1.getId());
                    tbProductWholeasalePrice.setPrice(new BigDecimal(string));
                    tbProductWholeasalePriceMapper.insertTbProductWholeasalePrice(tbProductWholeasalePrice);
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editProduct(JSONObject jsonObject) {
        ProductPlusVo productPlusVo=jsonObject.toJavaObject(ProductPlusVo.class);

        // 更新规格  更新批发价
        TbProductSpecification tbProductSpecification =new TbProductSpecification();
        tbProductSpecification.setProductPrice(productPlusVo.getProductPrice());
        tbProductSpecification.setProductSpecification(productPlusVo.getProductSpecification());
        tbProductSpecification.setProductUrl(productPlusVo.getProductUrl());
        tbProductSpecification.setId(productPlusVo.getSpecificationId());
        tbProductSpecificationMapper.updateTbProductSpecification(tbProductSpecification);

        TbProductWholeasalePrice tbProductWholeasalePrice = new TbProductWholeasalePrice();
        tbProductWholeasalePrice.setProductSpecification(tbProductSpecification.getId());
        List<TbProductWholeasalePrice> tbProductWholeasalePrices = tbProductWholeasalePriceMapper.selectTbProductWholeasalePriceList(tbProductWholeasalePrice);

        TbProductWholesale tbProductWholesale = new TbProductWholesale();
        tbProductWholesale.setProductTypeId(productPlusVo.getProductTypeId());
        List<TbProductWholesale> tbProductWholesales = tbProductWholesaleMapper.selectTbProductWholesaleList(tbProductWholesale);

        if (OConvertUtils.listIsNotEmpty(tbProductWholeasalePrices)){
            for (TbProductWholesale item:tbProductWholesales){
                String string = jsonObject.getString(item.getNum() + "+");
                if (OConvertUtils.isNotEmpty(string)){
                    for (TbProductWholeasalePrice productWholeasalePrice:tbProductWholeasalePrices){
                        if (productWholeasalePrice.getProductWholeasaleId().equals(item.getId())){
                            productWholeasalePrice.setPrice(new BigDecimal(string));
                            tbProductWholeasalePriceMapper.updateTbProductWholeasalePrice(productWholeasalePrice);
                        }
                    }
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeProducts(List<Long> ids) {
        Long[] id = ids.toArray(new Long[0]);
        tbProductSpecificationMapper.deleteTbProductSpecificationByIds(id);
        // 删除价位
        tbProductWholeasalePriceMapper.deleteTbProductWholeasalePriceBySpecificationIds(ids);
    }

    /**
     * 新增商品
     * 
     * @param tbProduct 商品
     * @return 结果
     */
    @Override
    public int insertTbProduct(TbProduct tbProduct)
    {
        tbProduct.setCreateTime(DateUtils.getNowDate());
        return tbProductMapper.insertTbProduct(tbProduct);
    }

    /**
     * 修改商品
     * 
     * @param tbProduct 商品
     * @return 结果
     */
    @Override
    public int updateTbProduct(TbProduct tbProduct)
    {
        return tbProductMapper.updateTbProduct(tbProduct);
    }

    /**
     * 批量删除商品
     * 
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteTbProductByIds(Long[] ids)
    {
        return tbProductMapper.deleteTbProductByIds(ids);
    }

    /**
     * 删除商品信息
     * 
     * @param id 商品主键
     * @return 结果
     */
    @Override
    public int deleteTbProductById(Long id)
    {
        return tbProductMapper.deleteTbProductById(id);
    }

    /**
     * 商品导出
     *
     * @param response
     * @param tbProduct
     */
    @Override
    public Workbook exportData( HttpServletResponse response,TbProduct tbProduct) throws URISyntaxException, IOException {
        // 查询需要导出的数据
        List<ExportTbProduct> list = tbProductMapper.queryExportData(tbProduct);
        // 查询导出数据的商品批发规格&价格
        List<Long> collect = list.stream().map(ExportTbProduct::getTypeId).collect(Collectors.toList());
        List<Long> specId = list.stream().map(ExportTbProduct::getId).collect(Collectors.toList());
        // 批发表规格表
        List<TbProductWholesale> tbProductWholesales = tbProductWholesaleMapper.selectTbproductWholesaleListByTypeIds(collect);
        // 批发价格表
        List<TbProductWholeasalePrice> tbProductWholeasalePrices= new ArrayList<>();
        // 通过批发量规格和商品ID 查询对应的价格
        if (OConvertUtils.listIsNotEmpty(tbProductWholesales)){
            List<Long> wholesalesIds = tbProductWholesales.stream().map(TbProductWholesale::getId).collect(Collectors.toList());
            //  查询单价  后续拼装导出excel
            tbProductWholeasalePrices = tbProductWholeasalePriceMapper.ListBySpecificationIdsAndWholeasaleId(specId, wholesalesIds);
        }


        // 关键优化：先按类别分组（一次性分组，避免多次遍历）
        Map<String, List<ExportTbProduct>> categoryMap = list.stream()
                .collect(Collectors.groupingBy(ExportTbProduct::getTypeName));

        // 创建工作簿
        Workbook workbook = new HSSFWorkbook();

        // 创建居中样式
        CellStyle centerStyle = workbook.createCellStyle();
        centerStyle.setAlignment(HorizontalAlignment.CENTER);
        centerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Font font = workbook.createFont();
        font.setBold(true);
        centerStyle.setFont(font);

        // 遍历每个类别分组（直接使用分组后的数据，无需再次筛选）
        for (Map.Entry<String, List<ExportTbProduct>> entry : categoryMap.entrySet()) {
            String category = entry.getKey(); // 类别名称
            List<ExportTbProduct> categoryProducts = entry.getValue(); // 该类别的所有商品

            // 创建工作表
            Sheet sheet = workbook.createSheet(category);

            // 1. 第一行：类别名称（合并居中）
            Row row1 = sheet.createRow(0);
            Cell categoryCell = row1.createCell(0);
            categoryCell.setCellValue(category);
            categoryCell.setCellStyle(centerStyle);


            String[] headers = {"商品编号", "商品名称", "商品类别", "商品规格", "商品链接", "商品单价"};
            List<TbProductWholesale> headerAddList = new ArrayList<>();
            // 判断当前列表是否有数据  --如果有数据则更具数据中内容添加多余批发字段
            if (OConvertUtils.listIsNotEmpty(categoryProducts)){
                ExportTbProduct exportTbProduct = categoryProducts.get(0);
                // 获取到类型ID
                Long typeId = exportTbProduct.getTypeId();
                // 规格ID
                Long specificationId = exportTbProduct.getId();
                // 获取当前商品的对应规格
                headerAddList = tbProductWholesales.stream().filter(tbProductWholesale -> tbProductWholesale.getProductTypeId().equals(typeId)).collect(Collectors.toList());
                for (TbProductWholesale tbProductWholesale : headerAddList) {
                    String[] strings = Arrays.copyOf(headers, headers.length + 1);
                    strings[headers.length] =tbProductWholesale.getNum()+"+";
                    headers= strings;
                }
            }
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length-1)); // 合并0-5列

            // 2. 第二行：表头
            Row row2 = sheet.createRow(1);
            for (int i = 0; i < headers.length; i++) {
                Cell cell = row2.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(centerStyle);
            }

            // 3. 数据行处理（直接使用当前类别的数据列表）
            int dataRowIndex = 2;
            String currentProductName = null;
            int mergeStartRow = dataRowIndex;

            // 按商品名称排序（确保同名称连续）
            categoryProducts.sort(Comparator.comparing(ExportTbProduct::getProductName));

            // 遍历当前类别的商品（无需再筛选，直接处理）
            for (int i = 0; i < categoryProducts.size(); i++) {
                ExportTbProduct product = categoryProducts.get(i);
                String productName = (product.getProductName() == null) ? "" : product.getProductName();

                // 首次处理或遇到新商品名称
                if (currentProductName == null) {
                    currentProductName = productName;
                    mergeStartRow = dataRowIndex;
                }
                // 遇到不同商品名称时检查合并
                else if (!currentProductName.equals(productName)) {
                    int rowCount = dataRowIndex - mergeStartRow;
                    if (rowCount >= 2) { // 至少2行才合并
                        sheet.addMergedRegion(new CellRangeAddress(mergeStartRow, dataRowIndex - 1, 1, 1));
                    }
                    currentProductName = productName;
                    mergeStartRow = dataRowIndex;
                }
                // 填充数据行
                Row dataRow = sheet.createRow(dataRowIndex);
                dataRow.createCell(0).setCellValue(product.getProductNo());
                Cell nameCell = dataRow.createCell(1);
                nameCell.setCellValue(productName);
                nameCell.setCellStyle(centerStyle);
                dataRow.createCell(2).setCellValue(category); // 直接使用当前类别，无需再从商品获取
                dataRow.createCell(3).setCellValue(product.getProductSpecification());
                dataRow.createCell(4).setCellValue(product.getProcutUrl());
                dataRow.createCell(5).setCellValue(OConvertUtils.isEmpty(product.getProductPrice())?"0.00":product.getProductPrice().toString());
                // 设置批发价
                int index =6; // 当前参数和最后一个设定值有关
                for (TbProductWholesale tbProductWholesale : headerAddList) {
                    // 批发规格ID
                    Long id = tbProductWholesale.getId();
                    // 商品规格ID
                    Long id1 = product.getId();
                    List<TbProductWholeasalePrice> priceList = tbProductWholeasalePrices.stream().filter(tbProductWholeasalePrice -> tbProductWholeasalePrice.getProductSpecification().equals(id1) &&
                            tbProductWholeasalePrice.getProductWholeasaleId().equals(id)).collect(Collectors.toList());
                    for (TbProductWholeasalePrice tbProductWholeasalePrice : priceList) {
                        dataRow.createCell(index).setCellValue(OConvertUtils.isEmpty(tbProductWholeasalePrice.getPrice())?"0.00":tbProductWholeasalePrice.getPrice().toString());
                        index++;
                    }
                }
                // 处理最后一组数据
                if (i == categoryProducts.size() - 1) {
                    int rowCount = dataRowIndex - mergeStartRow + 1;
                    if (rowCount >= 2) {
                        sheet.addMergedRegion(new CellRangeAddress(mergeStartRow, dataRowIndex, 1, 1));
                    }
                }
                dataRowIndex++;
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
        }

        return workbook;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int importProductData(List<ProductImportData> productList, String categoryName, boolean updateSupport) {
        int successCount = 0;
        // 1. 获取或创建商品类型
        Long productTypeId = getOrCreateProductType(categoryName);
        if (productTypeId == null){
            return 0;
        }

        for (ProductImportData importData : productList) {
            try {
                // 2. 处理商品基本信息
                TbProduct product = processProduct(importData, productTypeId, updateSupport);

                // 3. 处理商品规格
                TbProductSpecification specification = processSpecification(importData, product.getId(),updateSupport);

                // 4. 处理批发价格
                processWholesalePrices(importData, productTypeId, specification.getId(),updateSupport);

                successCount++;
            } catch (Exception e) {
                System.out.println(e.getMessage());
//                log.error("导入商品失败: {}, 错误: {}", importData.getProductName(), e.getMessage());
            }
        }

        return successCount;
    }

    @Resource
    private TbProductTypeMapper tbProductTypeMapper;

    private Long getOrCreateProductType(String categoryName) {
        // 查询是否存在该商品类型
        TbProductType queryType = new TbProductType();
        queryType.setTypeName(categoryName);
        List<TbProductType> types = tbProductTypeMapper.selectTbProductTypeList(queryType);

        if (!types.isEmpty()) {
            return types.get(0).getId();
        }
        //若不存在，则提示类别不存在
        return null;
    }

    @Resource
    private ITbProductSpecificationService tbProductSpecificationService;
    private TbProduct processProduct(ProductImportData importData, Long productTypeId, boolean updateSupport) {
        // 查询是否存在该商品
        List<TbProduct> products = tbProductMapper.selectTbProductListByProductNo(importData.getProductNo());
        TbProduct product =new TbProduct();
        product.setProductName(importData.getProductName());
        product.setProductTypeId(productTypeId);
        if (!products.isEmpty() && updateSupport) {
            // 更新现有商品
            product.setId(products.get(0).getId());
            product.setUpdateTime(DateUtils.getNowDate());
            product.setUpdateBy(getUsername());
            tbProductMapper.updateTbProduct(product);
        } else if (products.isEmpty()) {
            // 创建新商品
            product.setCreateTime(DateUtils.getNowDate());
            product.setCreateBy(getUsername());
            tbProductMapper.insertTbProduct(product);
        } else {
            // 商品已存在且不支持更新
            product = products.get(0);
        }

        return product;
    }

    private TbProductSpecification processSpecification(ProductImportData importData, Long productId, boolean updateSupport) {
        // 查询是否存在该规格
        TbProductSpecification querySpec = new TbProductSpecification();
        querySpec.setProductNo(importData.getProductNo());
        List<TbProductSpecification> specifications = tbProductSpecificationMapper.selectTbProductSpecificationList(querySpec);
        // 规格数据
        TbProductSpecification specification =new TbProductSpecification();
        specification.setProductNo(importData.getProductNo());
        specification.setProductId(productId);
        specification.setProductUrl(importData.getProductUrl());
        specification.setProductPrice(importData.getProductPrice());
        specification.setProductSpecification(importData.getProductSpecification());
        if (!specifications.isEmpty() && updateSupport) {
            specification.setId(specifications.get(0).getId());
            specification.setUpdateTime(DateUtils.getNowDate());
            specification.setUpdateBy(getUsername());
            //修改规格
            tbProductSpecificationMapper.updateTbProductSpecification(specification);

        } else if (specifications.isEmpty()) {
            // 创建新规格
            specification.setCreateTime(DateUtils.getNowDate());
            specification.setCreateBy(getUsername());
            tbProductSpecificationMapper.insertTbProductSpecification(specification);
        }

        return specification;
    }


    private void processWholesalePrices(ProductImportData importData, Long productTypeId, Long specificationId,boolean updateSupport) {
        Map<String, BigDecimal> wholesalePrices = importData.getWholesalePrices();

        for (Map.Entry<String, BigDecimal> entry : wholesalePrices.entrySet()) {
            String specification = entry.getKey(); // 如 "10+"
            BigDecimal price = entry.getValue();

            try {
                // 解析批发数量
                Long wholesaleNum = Long.parseLong(specification.replace("+", "").trim());
                // 获取或创建批发规格
                Long wholesaleId = getOrCreateWholesale(productTypeId, wholesaleNum,updateSupport);
                // 保存批发价格
                saveWholesalePrice(wholesaleId, specificationId, price);
            } catch (Exception e) {
                System.out.println(e.getMessage());
//                log.error("处理批发价格失败: {}, 错误: {}", specification, e.getMessage());
            }
        }
    }

    private Long getOrCreateWholesale(Long productTypeId, Long wholesaleNum,boolean updateSupport) {
        // 查询是否存在该批发规格
        TbProductWholesale queryWholesale = new TbProductWholesale();
        queryWholesale.setProductTypeId(productTypeId);
        queryWholesale.setNum(wholesaleNum);
        List<TbProductWholesale> wholesales = tbProductWholesaleMapper.selectTbProductWholesaleList(queryWholesale);
        // 创建新的批发规格
        TbProductWholesale newWholesale = new TbProductWholesale();
        newWholesale.setProductTypeId(productTypeId);
        newWholesale.setNum(wholesaleNum);
        if (!wholesales.isEmpty() && updateSupport) {
            newWholesale.setId(wholesales.get(0).getId());
            newWholesale.setUpdateTime(DateUtils.getNowDate());
            newWholesale.setUpdateBy(getUsername());
            tbProductWholesaleMapper.updateTbProductWholesale(newWholesale);
        } else if (wholesales.isEmpty()) {
            newWholesale.setCreateTime(DateUtils.getNowDate());
            newWholesale.setCreateBy(getUsername());
            tbProductWholesaleMapper.insertTbProductWholesale(newWholesale);
        }
        return newWholesale.getId();
    }

    private void saveWholesalePrice(Long wholesaleId, Long specificationId, BigDecimal price) {
        // 查询是否存在该价格记录
        TbProductWholeasalePrice queryPrice = new TbProductWholeasalePrice();
        queryPrice.setProductSpecification(specificationId);
        queryPrice.setProductWholeasaleId(wholesaleId);
        List<TbProductWholeasalePrice> prices = tbProductWholeasalePriceMapper.selectTbProductWholeasalePriceList(queryPrice);

        TbProductWholeasalePrice newPrice = new TbProductWholeasalePrice();
        newPrice.setProductWholeasaleId(wholesaleId);
        newPrice.setProductSpecification(specificationId);
        newPrice.setPrice(price);
        if (!prices.isEmpty()) {
            // 更新现有价格
            newPrice.setId(prices.get(0).getId());
            newPrice.setUpdateTime(DateUtils.getNowDate());
            newPrice.setUpdateBy(getUsername());
            newPrice.setPrice(price);
            tbProductWholeasalePriceMapper.updateTbProductWholeasalePrice(newPrice);
        } else {
            // 创建新价格记录
            newPrice.setCreateTime(DateUtils.getNowDate());
            newPrice.setCreateBy(getUsername());
            tbProductWholeasalePriceMapper.insertTbProductWholeasalePrice(newPrice);
        }
    }
}
